package app.framework.error;

import app.framework.constant.FrontConstants;
import app.framework.constant.FrameworkErrorConstants;
import app.framework.front.util.WebUtil;
import jasmine.framework.common.exception.ApplicationException;
import jasmine.framework.common.util.JsonUtil;
import jasmine.framework.web.entity.WebResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * 全局错误处理。
 * </p>
 *
 * @author mh.z
 */
public class GlobalExceptionResolver implements HandlerExceptionResolver {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionResolver.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
                                         Object handler, Exception ex) {
        WebResult result;
        logger.error("request failed", ex);

        if (ex instanceof ApplicationException) {
            ApplicationException appEx = (ApplicationException) ex;
            result = WebResult.error(appEx.getErrorCode(), appEx.getMessage());
        } else {
            result = WebResult.error(FrameworkErrorConstants.UNKNOWN_ERROR, ex.getMessage());
        }

        // 返回 JSON 结果
        WebUtil.setResponseInfo(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                FrontConstants.RESPONSE_CONTENT_TYPE_JSON);
        String json = JsonUtil.toJson(result);
        WebUtil.writeAndFlush(response, json);

        return new ModelAndView();
    }

}
